import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:html/parser.dart' as html_parser;
import 'package:html/dom.dart' as dom;
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class VersionIo {
  late BuildContext context;

  Future<http.Response> curl(String uri) async {
    debugPrint("curl: $uri");
    try {
      return await http.get(Uri.parse(uri));
    } catch (e) {
      debugPrint("请求失败: $e");
      rethrow;
    }
  }

  List<dom.Element> cssSelector(String html, String selector) {
    final document = html_parser.parse(html);
    final elements = document.querySelectorAll(selector);
    return elements;
  }

  Future<void> installApk(File apkFile) async {
    if (Platform.isAndroid) {
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('需要存储权限才能安装应用')),
        );
        return;
      }
    }

    await OpenFilex.open(apkFile.path);
  }

  Future<File?> downloadFile(String url, String fileName) async {
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        final directory = Platform.isAndroid
            ? await getExternalStorageDirectory()
            : await getApplicationDocumentsDirectory();
        
        final file = File('${directory?.path}/$fileName');
        await file.writeAsBytes(response.bodyBytes);
        return file;
      }
    } catch (e) {
      debugPrint("文件下载失败: $e");
    }
    return null;
  }
}
    